<template>
  <view class="my-total">
    <view class="one" @click="radioEvent">
      <label class="radio">
        <radio :checked="isAll" color="#c00000" /><text>全选</text>
      </label>
    </view>
    <view class="two">
      合计：<text>￥{{totalPrice}}</text>
    </view>
    <view class="three" @click="pay">
      结算（{{total}}）
    </view>
  </view>
</template>

<script>
  import {
    mapGetters,
    mapState
  } from 'vuex'
  export default {
    name: "my-total",
    data() {
      return {
        time: 0
      };
    },
    computed: {
      ...mapState('user', ['address', 'token']),
      ...mapState('cart', ['cart']),
      ...mapGetters('cart', ['isAll', 'total', 'totalPrice'])
    },
    methods: {
      radioEvent() {
        this.$store.commit('cart/setAllStatus', !this.isAll)
      },
      // 结算点击
      async pay() {
        // 1：已选择地址  2：有勾选商品  3:已登录
        // '{}'==='{}'   {}===>'{}'
        if (JSON.stringify(this.address) === '{}') {
          return uni.$showMsg('请先选择收货地址！')
        }
        if (this.total === 0) {
          return uni.$showMsg('请勾选需要购买商品！')
        }
        if (!this.token) {
          // return uni.$showMsg('请先登录！')
          // 倒计时跳转登录页
          // 提示
          // this.shoTip(3)
          // setTimeout(() => {
          //   this.shoTip(2)
          // }, 1000)
          // 倒计时处理
          return this.reTime()
        }
        // 满足支付条件
        // 1:创建订单
        const orderNumber = await this.createOrder()
        console.log('订单号', orderNumber);
        // 2：拿预支付信息
        const payInfo = await this.getPayInfo(orderNumber)
        // 3：调用支付api
        uni.requestPayment({
          ...payInfo,
          success: () => {
            // 清理购物车已支付的商品
            this.$store.commit('cart/reSetCart')
          }
        })


      },
      async createOrder() {
        const newGoods = this.cart.filter(item => item.goods_status).map(item => {
          return {
            goods_id: item.goods_id,
            goods_number: item.goods_count,
            goods_price: item.goods_price
          }
        })
        const res = await uni.$http.post('/my/orders/create', {
          data: {
            order_price: this.totalPrice,
            consignee_addr: `${this.address.provinceName}${this.address.cityName}${this.address.countyName}${this.address.detailInfo}`,
            goods: newGoods
          }
        })
        return res.message.order_number
        console.log('订单创建', res);
      },
      // 获取支付信息
      async getPayInfo(order_number) {
        const res = await uni.$http.post('/my/orders/req_unifiedorder', {
          data: {
            order_number: order_number
          }
        })
        return res.message.pay
        console.log('预支付信息', res);
      },
      shoTip(n) {
        uni.showToast({
          title: `您还没有登录，${n}秒后跳转至登录页`,
          icon: 'none',
          mask: true
        })
      },
      reTime() {
        this.time = 3
        this.shoTip(this.time)
        const timeId = setInterval(() => {
          this.time--
          this.shoTip(this.time)
          if (this.time <= 0) {
            clearInterval(timeId)
            // 跳转至登录页
            uni.switchTab({
              url: "/pages/my/my"
            })
            this.$store.commit('user/setBackRoute', {
              url: '/pages/cart/cart',
              type: 'switchTab'
            })
          }
        }, 1000)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .my-total {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100rpx;
    display: flex;
    align-items: center;
    background-color: #fff;
    z-index: 999;

    .one {
      flex: 2;
    }

    .two {
      flex: 3;

      text {
        color: #c00000;
      }
    }

    .three {
      flex: 2;
      height: 100rpx;
      background-color: #c00000;
      color: #fff;
      text-align: center;
      line-height: 100rpx;
    }
  }
</style>